package com.attendance.www.hr.service.impl;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Service;

import com.attendance.www.hr.beans.AttachmentBean;
import com.attendance.www.hr.dao.mapper.CorporationExtMapper;
import com.attendance.www.hr.dao.mapper.DepartmentExtMapper;
import com.attendance.www.hr.dao.mapper.DepartmentMapper;
import com.attendance.www.hr.entitys.Corporation;
import com.attendance.www.hr.entitys.Department;
import com.attendance.www.hr.entitys.DepartmentExample;
import com.attendance.www.hr.exception.ResultFaultException;
import com.attendance.www.hr.service.IDepartmentExcelService;

@Service
public class DepartmentExcelServiceImpl implements IDepartmentExcelService {

	@Resource
	private DepartmentMapper departmentDao;
	@Resource
	private DepartmentExtMapper departmentExtDao;
	@Resource
	private CorporationExtMapper corporationExtDao;

	private Map<String, Integer> addDepartmentMap;

	private Map<String, Integer> originalDepartmentMap;

	private Map<String, Department> departmentMap;

	private Map<String, Corporation> corporationMap;;

	/**
	 * 删除部门相关数据
	 * 
	 * @return
	 */
	@Override
	public boolean delDepartment() {
		return true;
	}

	@Override
	public List<String> importDepartment(Workbook work, AttachmentBean attachmentBean) {
		Calendar calendar = Calendar.getInstance(); // 得到日历
		calendar.setTime(attachmentBean.getFromDate());// 把当前时间赋给日历
		calendar.add(Calendar.DAY_OF_MONTH, -1); // 设置为前一天
		Date ThruDate = calendar.getTime(); // 得到前一天的时间
		Date oldThruDate = null;
		if (attachmentBean.getType() == 3) {

			DepartmentExample example = new DepartmentExample();
			DepartmentExample.Criteria criteria = example.createCriteria();
			criteria.andThruDateIsNull();
			Department department = new Department();
			department.setThruDate(ThruDate);
			departmentDao.updateByExampleSelective(department, example);
		}
		corporationMap = new HashMap<String, Corporation>();

		addDepartmentMap = new HashMap<String, Integer>();

		departmentMap = new HashMap<String, Department>();

		originalDepartmentMap = new HashMap<String, Integer>();

		List<String> successList = new ArrayList<String>();

		// 判断导入类型 1.覆盖 2.增量
		if (!(attachmentBean.getType() == 3)) {
			List<Department> departmentsList = departmentExtDao.getDepartmentListByExcel(attachmentBean);

			for (Department department : departmentsList) {
				departmentMap.put(department.getDepartmentCode(), department);
				addDepartmentMap.put(department.getDepartmentCode(), -1);
				oldThruDate = department.getThruDate();
			}

		}
		List<Corporation> corporationList = corporationExtDao.getCorporationListByExcel(attachmentBean);

		for (Corporation corporation : corporationList) {
			corporationMap.put(corporation.getCorporationCode(), corporation);
		}

		// 获取工作表的数量
		int sheetNum = work.getNumberOfSheets();
		// 遍历工作表 找出要导入的Excel表
		for (int m = 0; m < sheetNum; m++) {
			Sheet sh = work.getSheetAt(m);
			if (sh.getSheetName().equals("1.2部门")) {
				Sheet sheet = work.getSheetAt(m);
				List<String> errorMsgList = new ArrayList<String>();// 创建错误信息列表
				// 扫描Excel每行的每个单元格
				for (int i = 1; i <= sheet.getLastRowNum(); i++) {
					Department department = new Department();// 创建部门对象
					StringBuilder str = new StringBuilder("第" + (i + 1) + "行");
					Row row = sheet.getRow(i);
					// 如果一整行为空则忽略此行继续遍历
					if (row == null) {
						continue;
					}
					// 遍历某一行的所有列，如果此行每列都为空则跳过继续下一行
					boolean isNull = true;
					for (int c = 0; c < row.getLastCellNum(); c++) {
						if (row.getCell(c) == null || StringUtils.isBlank(row.getCell(c).toString())) {
							continue;
						} else {
							isNull = false;
						}
					}
					if (isNull) {
						continue;
					}
					if (oldThruDate != null) {
						if (oldThruDate.getTime() >= attachmentBean.getFromDate().getTime()) {
							department.setThruDate(oldThruDate);
						}
					}
					department.setFromDate(attachmentBean.getFromDate());
					if (attachmentBean.getType() == 1) {

						if (row.getCell(0) != null && StringUtils.isNotBlank(row.getCell(0).toString())) {
							String departmentCode = row.getCell(0).toString();
							if (originalDepartmentMap.containsKey(departmentCode)) {
								if (originalDepartmentMap.get(departmentCode).intValue() > 0) {
									str.append("与第" + originalDepartmentMap.get(departmentCode) + "行原部门编码("
											+ departmentCode + ")重复,");
								} else {
									str.append("原部门编码(" + departmentCode + ")已存在,");
								}
							} else {
								if (departmentMap.containsKey(departmentCode)) {
									department.setDepartmentId(departmentMap.get(departmentCode).getDepartmentId());
									department.setIsDisable(departmentMap.get(departmentCode).getIsDisable());
									originalDepartmentMap.put(row.getCell(0).toString(), i + 1);
								} else {
									str.append("原部门编码不存在,");
								}
							}
						} else {
							str.append("原部门编码不能为空,");
						}
					}
					department.setOrgLevel(1);
					// 判断第一列上级部门编码
					if (row.getCell(1) != null && StringUtils.isNotBlank(row.getCell(1).toString())) {
						String departmentCode = row.getCell(1).toString();
						// 根据部门编码查找在数据库中是否存在
						if (addDepartmentMap.containsKey(departmentCode)) {
							department.setParentDepartmentId(departmentMap.get(departmentCode).getDepartmentId());
							department.setOrgLevel(departmentMap.get(departmentCode).getOrgLevel()+1);
						} else {
							str.append("上级部门编码(" + departmentCode + ")不存在,");
						}
					}

					if (row.getCell(3) != null && StringUtils.isNotBlank(row.getCell(3).toString())) {
						String departmentCode = row.getCell(3).toString();
						department.setDepartmentCode(departmentCode);
						if (attachmentBean.getType() == 1 && row.getCell(0) != null
								&& StringUtils.isNotBlank(row.getCell(0).toString())) {
							String oldDepartmentCode = row.getCell(0).toString();
							if (addDepartmentMap.containsKey(departmentCode)
									&& !oldDepartmentCode.equals(departmentCode)) {
								if (addDepartmentMap.get(departmentCode) > 0) {
									str.append("与第" + addDepartmentMap.get(departmentCode) + "行部门编码(" + departmentCode
											+ ")重复,");
								} else {
									str.append("部门编码(" + departmentCode + ")已存在,");
								}
							} else {
								addDepartmentMap.put(department.getDepartmentCode(), i + 1);
							}
						} else {
							if (addDepartmentMap.containsKey(departmentCode)) {
								if (addDepartmentMap.get(departmentCode) > 0) {
									str.append("与第" + addDepartmentMap.get(departmentCode) + "行部门编码(" + departmentCode
											+ ")重复,");
								} else {
									str.append("部门编码(" + departmentCode + ")已存在,");
								}
							} else {
								addDepartmentMap.put(department.getDepartmentCode(), i + 1);
							}
						}
					} else {
						str.append("现部门编码不能为空,");
					}

					// 判断第二列部门名称的合法性
					if (row.getCell(4) != null && StringUtils.isNotBlank(row.getCell(4).toString())) {
						department.setDepartmentName(row.getCell(4).toString());
					} else {
						str.append("部门名称不能为空,");
					}


					// 第四列描述
					if (row.getCell(5) != null && StringUtils.isNotBlank(row.getCell(5).toString())) {
						String corporationCode = row.getCell(5).toString();
						if (corporationMap.containsKey(corporationCode)) {
							department.setCorporationId(corporationMap.get(corporationCode).getCorporationId());
						} else {
							str.append("所属公司编码不存在,");
						}
					} else {
						str.append("所属公司编码不能为空,");
					}

					// 第四列描述
					if (row.getCell(7) != null && StringUtils.isNotBlank(row.getCell(7).toString())) {
						department.setDescription(row.getCell(7).toString());
					}

					if (str.length() == new String("第" + (i + 1) + "行").length()) {
						// 判断导入类型 1.覆盖 2.增量
						boolean t = true;
						if (attachmentBean.getType() == 1) {
							department.setUpdateTime(new Date());
							department.setCreateTime(departmentMap.get(row.getCell(0).toString()).getCreateTime());
							departmentDao.updateByPrimaryKey(department);
							String success = str.toString() + "部门编码(" + department.getDepartmentCode() + ")";
							successList.add(success);
							t = false;

						}

						if (t) {
							try {
								// 添加
								departmentDao.insertSelective(department);
							} catch (Exception e) {
								throw new ResultFaultException("7_00002");
							}
						}
						if (row.getCell(1) != null&& StringUtils.isNotBlank(row.getCell(1).toString())) {
							department
									.setDepartmentPath(departmentMap.get(row.getCell(1).toString()).getDepartmentPath()
											+ department.getDepartmentId() + "-");

						} else {
							department.setDepartmentPath("-" + department.getDepartmentId() + "-");
						}
						departmentDao.updateByPrimaryKeySelective(department);

						// 将ID更改为行数
						if (!t) {
							if (row.getCell(0).toString() != row.getCell(3).toString()) {
								departmentMap.remove(row.getCell(0).toString());
								addDepartmentMap.remove(row.getCell(0).toString());
							}
						}
						addDepartmentMap.put(department.getDepartmentCode(), i + 1);
						departmentMap.put(department.getDepartmentCode(), department);
					} else {
						String errorStr = str.toString().substring(0, str.toString().length() - 1);
						errorMsgList.add(errorStr);
					}
				}
				if (errorMsgList.size() > 0) {
					throw new ResultFaultException("7_00002", errorMsgList);
				}

				if (successList.size() > 0) {
					successList.add(0, "部门导入完成,并覆盖数据如下：");
				} else {
					successList.add(0, "部门导入完成");
				}
				return successList;
			}
		}
		throw new ResultFaultException("7_00012");
	}
}
